package org.jeecgframework.web.system.controller.core;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.jeecgframework.core.common.controller.BaseController;
import org.jeecgframework.core.common.model.json.AjaxJson;
import org.jeecgframework.core.common.model.json.Highchart;
import org.jeecgframework.core.constant.Globals;
import org.jeecgframework.core.extend.datasource.DataSourceContextHolder;
import org.jeecgframework.core.extend.datasource.DataSourceType;
import org.jeecgframework.core.util.*;
import org.jeecgframework.web.service.ZyCommonService;
import org.jeecgframework.web.service.ZyInspectionPlanServiceI;
import org.jeecgframework.web.system.manager.ClientManager;
import org.jeecgframework.web.system.pojo.base.*;
import org.jeecgframework.web.system.service.MutiLangServiceI;
import org.jeecgframework.web.system.service.SystemService;
import org.jeecgframework.web.system.service.UserService;
import org.jeecgframework.web.util.StaticValue;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.view.RedirectView;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.*;

/**
 * 登陆初始化控制器
 */
@Scope("prototype")
@Controller
@RequestMapping("/loginController")
public class LoginController extends BaseController {
    private Logger log = Logger.getLogger(LoginController.class);
    private SystemService systemService;
    private UserService userService;
    private String message = null;
    @Autowired
    private ZyCommonService zyCommonService;

    @Autowired
    private MutiLangServiceI mutiLangService;

    @Autowired
    public void setSystemService(SystemService systemService) {
        this.systemService = systemService;
    }

    @Autowired
    public void setUserService(UserService userService) {

        this.userService = userService;
    }

    @RequestMapping(params = "goPwdInit")
    public String goPwdInit() {
        return "login/pwd_init";
    }

    /**
     * 检查用户名称
     *
     * @param user
     * @param req
     * @return
     */
    @RequestMapping(params = "checkuser")
    @ResponseBody
    public AjaxJson checkuser(TSUser user, HttpServletRequest req) {
        HttpSession session = ContextHolderUtils.getSession();
        DataSourceContextHolder
                .setDataSourceType(DataSourceType.dataSource_jeecg);
        AjaxJson j = new AjaxJson();
        // update-begin--Author:ken  Date:20140629 for：添加语言选择
        if (req.getParameter("langCode") != null) {
            req.getSession().setAttribute("lang", req.getParameter("langCode"));
        }
        // update-end--Author:ken  Date:20140629 for：添加语言选择
//        update-begin--Author:zhangguoming  Date:20140226 for：添加验证码
        String randCode = req.getParameter("randCode");
        if (StringUtils.isEmpty(randCode)) {
            j.setMsg("123");
            j.setSuccess(false);
        } else if (!randCode.equalsIgnoreCase(String.valueOf(session.getAttribute("randCode")))) {
            // todo "randCode"和验证码servlet中该变量一样，通过统一的系统常量配置比较好，暂时不知道系统常量放在什么地方合适
            j.setMsg(mutiLangService.getLang("common.validate.error"));
            j.setSuccess(false);
        } else {
//            update-end--Author:zhangguoming  Date:20140226 for：添加验证码
            int users = userService.getList(TSUser.class).size();

            if (users == 0) {
                j.setMsg("a");
                j.setSuccess(false);
            } else {
                TSUser u = userService.checkUserExits(user);
                if (null == u) {

                    u = userService.checkUserExitsByPhone(user);
                }
//                update-begin--Author:zhangguoming  Date:20140617 for：空指针bug
                if (u == null) {
                    j.setMsg(mutiLangService.getLang("common.username.or.password.error"));
                    j.setSuccess(false);
                    return j;
                }
//                update-end--Author:zhangguoming  Date:20140617 for：空指针bug
                TSUser u2 = userService.getEntity(TSUser.class, u.getId());

                if (u != null && u2.getStatus() != 0) {
                    // if (user.getUserKey().equals(u.getUserKey())) {


                    if (true) {
//                        update-start-Author:zhangguoming  Date:20140825 for：处理用户有多个组织机构的情况，以弹出框的形式让用户选择
                        Map<String, Object> attrMap = new HashMap<String, Object>();
                        j.setAttributes(attrMap);

                        String orgId = req.getParameter("orgId");
                        if (oConvertUtils.isEmpty(orgId)) { // 没有传组织机构参数，则获取当前用户的组织机构
                            Long orgNum = systemService.getCountForJdbc("select count(1) from t_s_user_org where user_id = '" + u.getId() + "'");
                            if (orgNum > 1) {
                                attrMap.put("orgNum", orgNum);
                                attrMap.put("user", u2);
                            } else {
                                Map<String, Object> userOrgMap = systemService.findOneForJdbc("select org_id as orgId from t_s_user_org where user_id=?", u2.getId());
                                saveLoginSuccessInfo(req, u2, (String) userOrgMap.get("orgId"));
                            }
                        } else {
                            attrMap.put("orgNum", 1);

                            saveLoginSuccessInfo(req, u2, orgId);
                        }
//                        update-end-Author:zhangguoming  Date:20140825 for：处理用户有多个组织机构的情况，以弹出框的形式让用户选择
                    } else {
                        j.setMsg(mutiLangService.getLang("common.check.shield"));
                        j.setSuccess(false);
                    }
                } else {
                    j.setMsg(mutiLangService.getLang("common.username.or.password.error"));
                    j.setSuccess(false);
                }
            }
//            update-begin--Author:zhangguoming  Date:20140226 for：添加验证码
        }
//        update-end--Author:zhangguoming  Date:20140226 for：添加验证码
        return j;
    }

//    update-start-Author:zhangguoming  Date:20140825 for：记录用户登录的相关信息

    /**
     * 保存用户登录的信息，并将当前登录用户的组织机构赋值到用户实体中；
     *
     * @param req   request
     * @param user  当前登录用户
     * @param orgId 组织主键
     */
    private void saveLoginSuccessInfo(HttpServletRequest req, TSUser user, String orgId) {

        TSDepart currentDepart = systemService.get(TSDepart.class, orgId);
        user.setCurrentDepart(currentDepart);
        HttpSession session = ContextHolderUtils.getSession();
        message = mutiLangService.getLang("common.user") + ": " + user.getUserName() + "["
                + currentDepart.getDepartname() + "]" + mutiLangService.getLang("common.login.success");

        Client client = new Client();
        client.setIp(IpUtil.getIpAddr(req));
        client.setLogindatetime(new Date());
        client.setUser(user);

        session.setAttribute("c_user_id", user.getId());
        session.setAttribute("c_depart_id", orgId);

        ClientManager.getInstance().addClinet(session.getId(), client);
        // 添加登陆日志
        systemService.addLog(message, Globals.Log_Type_LOGIN, Globals.Log_Leavel_INFO);
    }
//    update-end-Author:zhangguoming  Date:20140825 for：记录用户登录的相关信息

    /**
     * 用户登录
     *
     * @param request
     * @return
     */
    @RequestMapping(params = "login")
    public String login(ModelMap modelMap, HttpServletRequest request) {
        DataSourceContextHolder.setDataSourceType(DataSourceType.dataSource_jeecg);
        TSUser user = ResourceUtil.getSessionUserName();
        String roles = "";
        //request.getSession().setAttribute("lang", "zh-cn");//默认给 zh-cn ，因为首页修改了没有选择语言
        if (user != null) {
            List<TSRoleUser> rUsers = systemService.findByProperty(TSRoleUser.class, "TSUser.id", user.getId());
            //HD咨询线：满意度回访超时任务提醒：回访任务创建时间超过一周而未评价的回访任务。此数量包括巡检回访数量。
            Long cbs_inspection_evaluate_count = systemService.getCountForJdbc("select COUNT(*) from cbs_inspection_evaluate WHERE evaluate_state='1' and to_days(now())-to_days(create_date)>7 ");
            for (TSRoleUser ru : rUsers) {
                TSRole role = ru.getTSRole();
                roles += role.getRoleName() + ",";
                if (StaticValue.CHAIN_ROLE_LEADER.equals(role.getRoleCode())) {
                    modelMap.put("leader", 1);
                    if (user.getCurrentDepart() != null) {
                        String bpCode = user.getCurrentDepart().getBpCode();
                        String logo = userService.assebleChainLogo(bpCode);
                        if (StringUtil.isNotEmpty(logo)) {
                            modelMap.put("chainLogo", logo);
                        }
                    }
                } else if ("admin".equals(role.getRoleCode())) {
                    //服务单异常数量
                    Long i = systemService.getCountForJdbc("select count(*) from CBS_SERVICE_ERROR_LOG WHERE is_close = 1");
                    modelMap.put("CBS_SERVICE_ERROR_LOG_COUNT", i);
                    //序列号验证异常数量
                    Long j = systemService.getCountForJdbc("select count(*) from cbs_equipment_error_log where is_close = 1");
                    modelMap.put("CBS_SERVICE_ERROR_LOG__SN_COUNT", j);
                    modelMap.put("admin", 1);
                } else if (StaticValue.RULE_CODE_BARCO_CSA.equals(role.getRoleCode())) {
                    //CSA：待发货数量：发货单状态为“待CSA发货”和“欠货中”的发货单数量。
                    Long i = systemService.getCountForJdbc("select count(*) from cbs_deliver where status=1 or status=4");
                    modelMap.put("cbs_deliner_count", i);
                    //CSA：发货异常数量：未解决的发货异常数量。
                    Long j = systemService.getCountForJdbc("select count(*) from CBS_DELIVER_ERROR_LOG where is_close=1");
                    modelMap.put("CBS_DELIVER_ERROR_LOG_COUNT", j);
                    //CSA：返件异常数量：未解决的返件异常数量。
                    Long k = systemService.getCountForJdbc("select count(*) from cbs_back_error_log where is_close=1");
                    modelMap.put("CBS_BACK_ERROR_LOG_COUNT", k);
                    //CSA：序列号验证异常数量：未解决的序列号验证异常数量。
                    Long y = systemService.getCountForJdbc("select count(*) from cbs_equipment_error_log where is_close = 1");
                    modelMap.put("CBS_SERVICE_ERROR_LOG__SN_COUNT", y);
                    modelMap.put("barcoCSA", 1);
                } else if (StaticValue.CBS_HD_ROLE_CODE.equals(role.getRoleCode())) {
                    //HD组任务：服务单待处理数量：状态为“待处理”的服务单数量。
                    Long i = systemService.getCountForJdbc("select count(*) from CBS_SERVICE where status=1");
                    modelMap.put("CBS_SERVICE_COUNT", i);
                    //HD组任务：备件申请待处理数量：提交人为服务商工程师且状态为“待审批”的备件申请数量
                    Long j = systemService.getCountForJdbc("SELECT\n" +
                            "\tcount(*)\n" +
                            "FROM\n" +
                            "\tcbs_equipment_apply\n" +
                            "WHERE\n" +
                            "\tSTATUS = 1\n" +
                            "AND create_by IN (\n" +
                            "\tSELECT\n" +
                            "\t\tusername\n" +
                            "\tFROM\n" +
                            "\t\tt_s_base_user u\n" +
                            "\tLEFT JOIN t_s_role_user ru ON u.id = ru.userid\n" +
                            "\tLEFT JOIN t_s_role r ON r.id = ru.roleid\n" +
                            "\tWHERE\n" +
                            "\t\tr.rolename = '服务商工程师' or r.rolename = '服务商区域工程师'\n" +
                            ")");
                    modelMap.put("cbs_equipment_apply_COUNT", j);
                    //HD我的任务：服务单待处理数量：在本人名下且状态为“已受理”的服务单数量
                    Long x = systemService.getCountForJdbc("select count(*) from CBS_SERVICE where status=2 and person_liable='" + ru.getTSUser().getId() + "'");
                    modelMap.put("CBS_SERVICE_1_COUNT", x);
                    //HD我的任务：服务单处理中数量：在本人名下且状态为“处理中”的服务单数量
                    Long y = systemService.getCountForJdbc("select count(*) from CBS_SERVICE where status=3 and person_liable='" + ru.getTSUser().getId() + "'");
                    modelMap.put("CBS_SERVICE_2_COUNT", y);
                    modelMap.put("barcoHelpdesk", 1);
                }
            }
            if (roles.length() > 0) {
                roles = roles.substring(0, roles.length() - 1);
            }
            modelMap.put("roleName", roles);
            modelMap.put("realName", user.getRealName());
            // update-start-Author:zhangguoming  Date:20140914 for：获取当前登录用户的组织机构
            modelMap.put("currentOrgName", ClientManager.getInstance().getClient().getUser().getCurrentDepart().getDepartname());
            // update-end-Author:zhangguoming  Date:20140914 for：获取当前登录用户的组织机构
            request.getSession().setAttribute("CKFinder_UserRole", "admin");


            // 默认风格
            String indexStyle = "shortcut";
            Cookie[] cookies = request.getCookies();
            for (Cookie cookie : cookies) {
                if (cookie == null || StringUtils.isEmpty(cookie.getName())) {
                    continue;
                }
                if (cookie.getName().equalsIgnoreCase("JEECGINDEXSTYLE")) {
                    indexStyle = cookie.getValue();
                }
            }
            // 要添加自己的风格，复制下面三行即可
            if (StringUtils.isNotEmpty(indexStyle)
                    && indexStyle.equalsIgnoreCase("bootstrap")) {
                return "main/bootstrap_main";
            }
            if (StringUtils.isNotEmpty(indexStyle)
                    && indexStyle.equalsIgnoreCase("shortcut")) {
                return "main/shortcut_main";
            }

//			update-start--Author:gaofeng  Date:2014-01-24 for:新增首页风格按钮选项
            if (StringUtils.isNotEmpty(indexStyle)
                    && indexStyle.equalsIgnoreCase("sliding")) {
                return "main/sliding_main";
            }
//			update-start--Author:gaofeng  Date:2014-01-24 for:新增首页风格按钮选项

            return "main/main";
        } else {
            return "login/login_new";
        }

    }

    /**
     * 退出系统
     *
     * @param request
     * @return
     */
    @RequestMapping(params = "logout")
    public ModelAndView logout(HttpServletRequest request) {
        HttpSession session = ContextHolderUtils.getSession();
        ClientManager.getInstance().removeClinet(session.getId());
        session.removeAttribute("userClient");
        session.invalidate();
        ModelAndView modelAndView = new ModelAndView(new RedirectView(
                "loginController.do?login"));
        return modelAndView;
    }

    /**
     * 菜单跳转
     *
     * @return
     */
    @RequestMapping(params = "left")
    public ModelAndView left(HttpServletRequest request) {
        TSUser user = ResourceUtil.getSessionUserName();
        HttpSession session = ContextHolderUtils.getSession();
        ModelAndView modelAndView = new ModelAndView();
        // 登陆者的权限
        if (user.getId() == null) {
            session.removeAttribute(Globals.USER_SESSION);
            modelAndView.setView(new RedirectView("loginController.do?login"));
        } else {
            List<TSConfig> configs = userService.loadAll(TSConfig.class);
            for (TSConfig tsConfig : configs) {
                request.setAttribute(tsConfig.getCode(), tsConfig.getContents());
            }
            modelAndView.setViewName("main/left");
            request.setAttribute("menuMap", getFunctionMap(user));
        }
        return modelAndView;
    }

    /**
     * 获取权限的map
     *
     * @param user
     * @return
     */
    private Map<Integer, List<TSFunction>> getFunctionMap(TSUser user) {
        Map<Integer, List<TSFunction>> functionMap = new HashMap<Integer, List<TSFunction>>();
        Map<String, TSFunction> loginActionlist = getUserFunction(user);
        if (loginActionlist.size() > 0) {
            Collection<TSFunction> allFunctions = loginActionlist.values();
            for (TSFunction function : allFunctions) {
                //update-begin--Author:anchao  Date:20140913 for：菜单过滤--------------------
                if (StringUtil.isNotEmpty(function.getFunctionType())) {
                    if (function.getFunctionType().intValue() == Globals.Function_TYPE_FROM.intValue()) {
                        //如果为表单或者弹出 不显示在系统菜单里面
                        continue;
                    }
                }
                //update-end--Author:anchao  Date:20140913 for：菜单过滤--------------------
                if (!functionMap.containsKey(function.getFunctionLevel() + 0)) {
                    functionMap.put(function.getFunctionLevel() + 0,
                            new ArrayList<TSFunction>());
                }
                functionMap.get(function.getFunctionLevel() + 0).add(function);
            }
            // 菜单栏排序
            Collection<List<TSFunction>> c = functionMap.values();
            for (List<TSFunction> list : c) {
                Collections.sort(list, new NumberComparator());
            }
        }
        return functionMap;
    }

    /**
     * 获取用户菜单列表
     *
     * @param user
     * @return
     */
    private Map<String, TSFunction> getUserFunction(TSUser user) {
        HttpSession session = ContextHolderUtils.getSession();
        Client client = ClientManager.getInstance().getClient(session.getId());
//		System.out.println("client "+user.getUserName()+" functions:"+client.getFunctions());
//		System.out.println("client id "+user.getId());
//		System.out.println("org id "+client.getUser().getCurrentDepart().getId());
        //update-start--Author:JueYue  Date:2014-5-28 for:风格切换,菜单懒加载失效的问题
        if (client.getFunctions() == null || client.getFunctions().size() == 0) {
            //update-end--Author:JueYue  Date:2014-5-28 for:风格切换,菜单懒加载失效的问题
            Map<String, TSFunction> loginActionlist = new HashMap<String, TSFunction>();
            List<TSRoleUser> rUsers = systemService.findByProperty(TSRoleUser.class, "TSUser.id", user.getId());
//			System.out.println("client users:"+rUsers.size());
//            update-begin--Author:zhangguoming  Date:20140821 for：重构方法体，并加载用户组织机构下角色所拥有的权限
            for (TSRoleUser ru : rUsers) {
                TSRole role = ru.getTSRole();
                assembleFunctionsByRole(loginActionlist, role);
            }
//            update-start-Author:zhangguoming  Date:20140825 for：获取当前登录用户的组织机构主键
            String orgId = client.getUser().getCurrentDepart().getId();
//			System.out.println("org Id:"+orgId);
//            update-end-Author:zhangguoming  Date:20140825 for：获取当前登录用户的组织机构主键
            List<TSRoleOrg> orgRoleList = systemService.findByProperty(TSRoleOrg.class, "tsDepart.id", orgId);
//			System.out.println("org list :"+orgRoleList.size());
            for (TSRoleOrg roleOrg : orgRoleList) {
                TSRole role = roleOrg.getTsRole();
                assembleFunctionsByRole(loginActionlist, role);
            }
//            update-end--Author:zhangguoming  Date:20140821 for：重构方法体，并加载用户组织机构下角色所拥有的权限
//			System.out.println("login action list:"+loginActionlist);
            client.setFunctions(loginActionlist);
        }
        return client.getFunctions();
    }

//    update-begin--Author:zhangguoming  Date:20140821 for：抽取方法，获取角色下的权限列表

    /**
     * 根据 角色实体 组装 用户权限列表
     *
     * @param loginActionlist 登录用户的权限列表
     * @param role            角色实体
     */
    private void assembleFunctionsByRole(Map<String, TSFunction> loginActionlist, TSRole role) {
        List<TSRoleFunction> roleFunctionList = systemService.findByProperty(TSRoleFunction.class, "TSRole.id", role.getId());
        for (TSRoleFunction roleFunction : roleFunctionList) {
            TSFunction function = roleFunction.getTSFunction();
            //update-begin--Author:anchao  Date:20140822 for：[bugfree号]字段级权限（表单，列表）--------------------
            if (function.getFunctionType().intValue() == Globals.Function_TYPE_FROM.intValue()) {
                //如果为表单或者弹出 不显示在系统菜单里面
                continue;
            }
            //update-end--Author:anchao  Date:20140822 for：[bugfree号]字段级权限（表单，列表）--------------------
            loginActionlist.put(function.getId(), function);
        }
    }
//    update-end--Author:zhangguoming  Date:20140821 for：抽取方法，获取角色下的权限列表

    /**
     * 首页跳转
     *
     * @return
     */
    @RequestMapping(params = "home")
    public ModelAndView home(HttpServletRequest request) {
        TSUser user = ResourceUtil.getSessionUserName();
        List<TSRoleUser> tsRoleUsers = systemService.findByProperty(TSRoleUser.class, "TSUser.id", user.getId());
        boolean hasView = false, barHasView = false;
        List<String> currYearIpProgressRole = new ArrayList<String>();//本年度巡检进度饼图 权限
        currYearIpProgressRole.add(StaticValue.RULE_CODE_BARCO_SERVER_DIRECTOR);
        currYearIpProgressRole.add(StaticValue.RULE_CODE_BARCO_SERVER_CHARGE);
        currYearIpProgressRole.add(StaticValue.RULE_CODE_BARCO_CHIEF_INSPECTORS);
        currYearIpProgressRole.add(StaticValue.RULE_CODE_BARCO_CS_DIRECTOR);
        currYearIpProgressRole.add(StaticValue.RULE_CODE_BARCO_CS_MANAGER);
        currYearIpProgressRole.add("admin");
        boolean hasEsIpView = false;
        List<String> esIpRole = new ArrayList<String>();//巡检情况柱状图权限
        esIpRole.add(StaticValue.RULE_CODE_BARCO_SERVER_DIRECTOR);
        esIpRole.add(StaticValue.RULE_CODE_BARCO_CS_DIRECTOR);
        esIpRole.add(StaticValue.RULE_CODE_BARCO_CSE_MANAGER);
        esIpRole.add("admin");
        boolean containerView = false;
        List<String> containerRole = new ArrayList<String>();//服务单实时数量图权限
        containerRole.add(StaticValue.CBS_HD_ROLE_CODE);
        containerRole.add("admin");
        for (TSRoleUser tsRoleUser : tsRoleUsers) {
            String roleCode = tsRoleUser.getTSRole().getRoleCode();
            if (currYearIpProgressRole.contains(roleCode)) {
                hasView = true;
                if (roleCode.equals(StaticValue.RULE_CODE_BARCO_CS_MANAGER)) {
                    barHasView = true;
                }
            }
            if (esIpRole.contains(roleCode)) {
                hasEsIpView = true;
            }
            if (containerRole.contains(roleCode)) {
                containerView = true;
            }
        }
        request.setAttribute("hasEsIpView", hasEsIpView);
        request.setAttribute("hasView", hasView);
        request.setAttribute("containerView", containerView);
        request.setAttribute("barHasView", barHasView);
        return new ModelAndView("main/home");
    }

    /**
     * 院线用户 首页跳转
     *
     * @return
     */
    @RequestMapping(params = "chainHome")
    public ModelAndView chainHome(HttpServletRequest request) {
        //再次判断用户是否是院线角色
        TSUser user = ResourceUtil.getSessionUserName();
        if (userService.hasRole(user.getUserName(), StaticValue.CHAIN_ROLE_LEADER)) {//院线用户
            return new ModelAndView("main/chainHome");
        }
        return new ModelAndView("main/home");
    }

    /**
     * @author xiul
     * 2016-5-9 上午10:48:49
     * Description 首页 - 本年度巡检进度饼图数据
     */
    @ResponseBody
    @RequestMapping(params = "getCurrYearInspectionsHighChartData")
    public List<Highchart> getCurrYearInspectionsHighChartData(HttpServletRequest req) {
        String type = req.getParameter("type");
        return zyCommonService.queryIpsHighChartData(type);
    }

    /**
     * @author xiul
     * 2016-5-9 下午2:35:32
     * Description 查询 home 页 待办事项以及任务提醒数据
     */
    @ResponseBody
    @RequestMapping(params = "queryHomePageData")
    public AjaxJson queryHomePageData(HttpServletRequest req) {
        AjaxJson j = new AjaxJson();
        try {
            zyCommonService.queryHomePageData(j, req);
        } catch (Exception e) {
            j.setSuccess(false);
            j.setMsg("待办数据查询异常");
            e.printStackTrace();
        }
        return j;
    }

    /**
     * @author xiul
     * 2016-5-9 下午2:35:32
     * Description 查询 home 页 待办事项以及任务提醒数据(服务单)
     */
    @ResponseBody
    @RequestMapping(params = "queryHomePageServiceData")
    public AjaxJson queryHomePageServiceData(HttpServletRequest req) {
        AjaxJson j = new AjaxJson();
        try {
            zyCommonService.queryHomePageServiceData(j, req);
        } catch (Exception e) {
            j.setSuccess(false);
            j.setMsg("待办数据查询异常");
            e.printStackTrace();
        }
        return j;
    }

    /**
     * 无权限页面提示跳转
     *
     * @return
     */
    @RequestMapping(params = "noAuth")
    public ModelAndView noAuth(HttpServletRequest request) {
        return new ModelAndView("common/noAuth");
    }

    /**
     * @param request
     * @return ModelAndView
     * @throws
     * @Title: top
     * @Description: bootstrap头部菜单请求
     */
    @RequestMapping(params = "top")
    public ModelAndView top(HttpServletRequest request) {
        TSUser user = ResourceUtil.getSessionUserName();
        HttpSession session = ContextHolderUtils.getSession();
        // 登陆者的权限
        if (user.getId() == null) {
            session.removeAttribute(Globals.USER_SESSION);
            return new ModelAndView(
                    new RedirectView("loginController.do?login"));
        }
        request.setAttribute("menuMap", getFunctionMap(user));
        List<TSConfig> configs = userService.loadAll(TSConfig.class);
        for (TSConfig tsConfig : configs) {
            request.setAttribute(tsConfig.getCode(), tsConfig.getContents());
        }
        return new ModelAndView("main/bootstrap_top");
    }

    /**
     * @param request
     * @return ModelAndView
     * @throws
     * @Title: top
     * @author gaofeng
     * @Description: shortcut头部菜单请求
     */
    @RequestMapping(params = "shortcut_top")
    public ModelAndView shortcut_top(HttpServletRequest request) { // NOPMD by dzqThinkpad on 16-4-1 下午3:26
        TSUser user = ResourceUtil.getSessionUserName();
        HttpSession session = ContextHolderUtils.getSession();
        // 登陆者的权限
        if (user.getId() == null) {
            session.removeAttribute(Globals.USER_SESSION);
            return new ModelAndView(
                    new RedirectView("loginController.do?login"));
        }
        request.setAttribute("menuMap", getFunctionMap(user));
        List<TSConfig> configs = userService.loadAll(TSConfig.class);
        for (TSConfig tsConfig : configs) {
            request.setAttribute(tsConfig.getCode(), tsConfig.getContents());
        }
        return new ModelAndView("main/shortcut_top");
    }

    /**
     * @return AjaxJson
     * @throws
     * @Title: top
     * @author:gaofeng
     * @Description: shortcut头部菜单一级菜单列表，并将其用ajax传到页面，实现动态控制一级菜单列表
     */
    @RequestMapping(params = "primaryMenu")
    @ResponseBody
    public String getPrimaryMenu() {
        List<TSFunction> primaryMenu = getFunctionMap(ResourceUtil.getSessionUserName()).get(0);
        String floor = "";
        for (TSFunction function : primaryMenu) {
            if (function.getFunctionLevel() == 0) {

                String langKey = function.getFunctionName();
                String langContext = mutiLangService.getLang(langKey);

                if ("Online 开发".equals(langContext)) {

                    floor += " <li><img class='imag1' src='plug-in/login/images/menuicon_03.png' /> "
                            + " <img class='imag2' src='plug-in/login/images/menuicon_00_03.png' style='display: none;' />" + " </li> ";
                } else if ("服务单管理".equals(langContext)) {

                    floor += " <li><img class='imag1' src='plug-in/login/images/service_001.png' /> "
                            + " <img class='imag2' src='plug-in/login/images/service.png' style='display: none;' />"
                            + "<div style='width:67px;position: absolute;top:60px;text-align:center;color:#FFFFFF;font-size:12px;'>" + langContext + "</div> " + "</li> ";
                } else if ("异常处理".equals(langContext)) {

                    floor += " <li><img class='imag1' src='plug-in/login/images/error_001.png' /> "
                            + " <img class='imag2' src='plug-in/login/images/error.png' style='display: none;' />"
                            + "<div style='width:67px;position: absolute;top:60px;text-align:center;color:#FFFFFF;font-size:12px;'>" + langContext + "</div> " + "</li> ";
                } else if ("巡检管理".equals(langContext)) {

                    floor += " <li><img class='imag1' src='plug-in/login/images/menuicon_001.png' /> "
                            + " <img class='imag2' src='plug-in/login/images/menuicon_focus_001.png' style='display: none;' />"
                            + "<div style='width:67px;position: absolute;top:60px;text-align:center;color:#FFFFFF;font-size:12px;'>" + langContext + "</div> " + "</li> ";
                } else if ("设备管理".equals(langContext)) {
                    floor += " <li><img class='imag1' src='plug-in/login/images/menuicon_002.png' /> "
                            + " <img class='imag2' src='plug-in/login/images/menuicon_focus_002.png' style='display: none;' />"
                            + "<div style='width:67px;position: absolute;top:60px;text-align:center;color:#FFFFFF;font-size:12px;'>" + langContext + "</div> " + "</li> ";
                } else if ("客户管理".equals(langContext)) {
                    floor += " <li><img class='imag1' src='plug-in/login/images/menuicon_004.png' /> "
                            + " <img class='imag2' src='plug-in/login/images/menuicon_focus_004.png' style='display: none;' />"
                            + "<div style='width:67px;position: absolute;top:60px;text-align:center;color:#FFFFFF;font-size:12px;'>" + langContext + "</div> " + "</li> ";
                } else if ("报表统计".equals(langContext)) {
                    floor += " <li><img class='imag1' src='plug-in/login/images/menuicon_005.png' /> "
                            + " <img class='imag2' src='plug-in/login/images/menuicon_focus_005.png' style='display: none;' />"
                            + "<div style='width:67px;position: absolute;top:60px;text-align:center;color:#FFFFFF;font-size:12px;'>" + langContext + "</div> " + "</li> ";
                } else if ("巡检报告".equals(langContext)) {
                    floor += " <li><img class='imag1' src='plug-in/login/images/menuicon_005.png' /> "
                            + " <img class='imag2' src='plug-in/login/images/menuicon_focus_005.png' style='display: none;' />"
                            + "<div style='width:67px;position: absolute;top:60px;text-align:center;color:#FFFFFF;font-size:12px;'>" + langContext + "</div> " + "</li> ";
                } else if ("系统管理".equals(langContext)) {
                    floor += " <li><img class='imag1' src='plug-in/login/images/menuicon_003.png' /> "
                            + " <img class='imag2' src='plug-in/login/images/menuicon_focus_003.png' style='display: none;' />"
                            + "<div style='width:67px;position: absolute;top:60px;text-align:center;color:#FFFFFF;font-size:12px;'>" + langContext + "</div> " + "</li> ";
                } else {
                    //其他的为默认通用的图片模式
                    String s = "";
                    if (langContext.length() >= 5 && langContext.length() < 7) {
                        s = "<div style='width:67px;position: absolute;top:40px;text-align:center;color:#FFFFFF;font-size:12px;'><span style='letter-spacing:-1px;'>" + langContext + "</span></div>";
                    } else if (langContext.length() < 5) {
                        s = "<div style='width:67px;position: absolute;top:40px;text-align:center;color:#FFFFFF;font-size:12px;'>" + langContext + "</div>";
                    } else if (langContext.length() >= 7) {
                        s = "<div style='width:67px;position: absolute;top:40px;text-align:center;color:#FFFFFF;font-size:12px;'><span style='letter-spacing:-1px;'>" + langContext.substring(0, 6) + "</span></div>";
                    }
                    floor += " <li style='position: relative;'><img class='imag1' src='plug-in/login/images/menuicon_03.png' /> "
                            + " <img class='imag2' src='plug-in/login/images/menuicon_00_03.png' style='display: none;' />"
                            + s + "</li> ";
                }
            }
        }

        return floor;
    }


    /**
     * 返回数据
     */
    @RequestMapping(params = "getPrimaryMenuForWebos")
    @ResponseBody
    public AjaxJson getPrimaryMenuForWebos() {
        AjaxJson j = new AjaxJson();
        //将菜单加载到Session，用户只在登录的时候加载一次
        Object getPrimaryMenuForWebos = ContextHolderUtils.getSession().getAttribute("getPrimaryMenuForWebos");
        if (oConvertUtils.isNotEmpty(getPrimaryMenuForWebos)) {
            j.setMsg(getPrimaryMenuForWebos.toString());
        } else {
            String pMenu = ListtoMenu.getWebosMenu(getFunctionMap(ResourceUtil.getSessionUserName()));
            ContextHolderUtils.getSession().setAttribute("getPrimaryMenuForWebos", pMenu);
            j.setMsg(pMenu);
        }
        return j;
    }
}